package valid

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
)

func ValidAddAdmin(admin map[string]interface{}) (bool, string) {
	valid := validation.Validation{}

	v := valid.Required(admin["user_name"], "user_name").Message("用户名不能为空")
	if !v.Ok {
		return false, v.Error.Message
	}
	v = valid.Required(admin["password"], "password").Message("密码不能为空")
	if !v.Ok {
		return false, v.Error.Message
	}

	ps := getQueryTable("admin")
	ext := ps.Filter("user_name", admin["user_name"]).Exist()
	if ext {
		return false, "用户名已存在"
	}

	return true, ""
}

func ValidEditAdmin(admin map[string]interface{}) (bool, string) {
	//valid := validation.Validation{}
	if admin["user_name"] != nil {
		sql := "SELECT id from admin where id <> ? and user_name = ? limit 0,1"
		type idExist struct {
			Id int64
		}
		isId := idExist{}
		o := orm.NewOrm()
		_ = o.Raw(sql, admin["id"], admin["user_name"]).QueryRow(&isId)
		if isId.Id != 0 {
			return false, "用户名已存在"
		}
	}
	return true, ""
}
